package com.huaweicloud.filter;

import com.huaweicloud.commons.outhUtils.JwtUtil;
import com.huaweicloud.commons.response.ResultCode;
import com.huaweicloud.config.URIFilter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class PreTypeFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(PreTypeFilter.class);

    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    URIFilter uriFilter;

    @Override
    public String filterType() {

        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 1、获取到request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI();
        // 2、登陆请求放行
        if(request.getRequestURI().contains(uriFilter.getLoginuri().get(0))){
            System.out.println("登陆请求：request.getRequestURI() = " + requestURI);
            return false;
        }
        //3、非登陆请求用户权限校验
        if (!StringUtils.isEmpty(request.getHeader("Authorization"))) {
            System.out.println("非登陆请求：request.getRequestURI() = " + requestURI);
            return true;
        }
        return false;
    }

    @Override
    public Object run()  {

        // 1、获取到request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String authorization = request.getHeader("Authorization");

        System.out.println("非登陆请求：request.getRequestURI() = " + request.getRequestURI());
        //2、获取请求头中Token信息
        String token = authorization.replace("Bearer", "");

        //3、Token校验
        Claims claims = jwtUtil.parseToken(token) ;

        //4、获取用户id，并将用户id传送到后端
        if (claims == null) {
            try {
                throw new Exception(String.valueOf(ResultCode.UNAUTHENTICATED));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return  null;
        }
        String id = claims.getId();
        //5、添加用户请求头
        ctx.addZuulRequestHeader("userId",id);

        ctx.setSendZuulResponse(true);
        ctx.set("isSuccess", true);

        return null;
    }
}
